package ide.ccf.ccproject.editors;

import java.util.ArrayList;

import org.eclipse.jface.action.Action;
import org.eclipse.swt.widgets.Event;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.actions.ActionFactory;


/**
 * CCF项目文件编辑器动作类
 *
 */
class ProjectFileEditorAction extends Action
{
	private ProjectFileEditorActionContributor m_cont;
	private int m_id;
	private int m_lastevent;
	
	/**
	 * 构造器
	 * @param cont
	 * @param id
	 */
	public ProjectFileEditorAction(ProjectFileEditorActionContributor cont, int id) 
	{
		super();
		
		m_cont = cont;
		m_id = id;
		m_lastevent = 0;
		
		setEnabled(m_cont.activeEditor().isActionEnabled(m_id));
	}
	
	/**
	 * 运行
	 */
	public void runWithEvent(Event event) 
	{
		if (event.time != m_lastevent) 
		{
			m_lastevent = event.time;
			run();
		}
	}
	
	/**
	 * 运行
	 */
	public void run() 
	{
		m_cont.activeEditor().triggerAction(m_id);
	}
}

/**
 * CCF项目文件编辑器动作构建器
 *
 */
public class ProjectFileEditorActionContributor implements IEditorActionBarContributor
{
	@SuppressWarnings("rawtypes")
	private ArrayList actions = null;
	private IActionBars actionbars;
	private ProjectFileEditor editor;
	
	/**
	 * 设置要激活的编辑器
	 */
	public void setActiveEditor(IEditorPart targetEditor)
	{
		if (targetEditor instanceof ProjectFileEditor)
		{
			editor = ((ProjectFileEditor)targetEditor);
			
			if (actions == null)
				setupActions();
		}
	}
	
	/**
	 * 获取激活的编辑器
	 * @return
	 */
	public ProjectFileEditor activeEditor()
	{
		return editor;		
	}
	
	/**
	 * 初始化
	 */
	public void init(IActionBars bars, IWorkbenchPage page)
	{
		actionbars = bars;
	}
	
	/**
	 * 释放
	 */
	public void dispose()
	{
	}
	
	/**
	 * 构建动作
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void setupActions()
	{
		actions = new ArrayList();
	
		ProjectFileEditorAction act = new ProjectFileEditorAction(this, 0);
		actionbars.setGlobalActionHandler(ActionFactory.CUT.getId(), act);
		actions.add(act);

		act = new ProjectFileEditorAction(this, 1);
		actionbars.setGlobalActionHandler(ActionFactory.COPY.getId(), act);
		actions.add(act);

		act = new ProjectFileEditorAction(this, 2);
		actionbars.setGlobalActionHandler(ActionFactory.PASTE.getId(), act);
		actions.add(act);

		act = new ProjectFileEditorAction(this, 3);
		actionbars.setGlobalActionHandler(ActionFactory.UNDO.getId(), act);
		actions.add(act);

		act = new ProjectFileEditorAction(this, 4);
		actionbars.setGlobalActionHandler(ActionFactory.REDO.getId(), act);
		actions.add(act);
	}
	
	/**
	 * 动作栏
	 * @return
	 */
	public IActionBars actionBars()
	{
        return actionbars;
	}
	
	/**
	 * 更新
	 * @param actId
	 */
	public void updateAction(int actId)
	{
		if (actions != null) 
		{
			((ProjectFileEditorAction)actions.get(actId)).setEnabled(editor.isActionEnabled(actId));
		}
	}	
}
